package com.itzzy.dice.config;

import cn.hutool.core.util.RandomUtil;
import com.github.benmanes.caffeine.cache.Cache;
import com.itzzy.dice.bean.entity.PlayerInfo;
import com.itzzy.dice.bean.entity.RoomInfo;
import xyz.noark.core.annotation.Autowired;
import xyz.noark.core.annotation.Component;

/**
 * Caffeine缓存工具类
 *
 * @Author gblfy
 * @Date 2022-03-15 14:58
 **/
@Component
public class CaffeineUtils {

    @Autowired
    Cache<String, RoomInfo> caffeineCache;

    @Autowired
    Cache<String, String> playerRoomCache;

    /**
     * 添加房间
     */
    public void putDataCache(String key, RoomInfo roomInfo){
        caffeineCache.put(key, roomInfo);
    }

    /**
     * 添加或更新缓存
     */
    public void addPlayerToCache(String key, PlayerInfo playerInfo) {
        RoomInfo roomInfo = caffeineCache.getIfPresent(key);
        if (roomInfo.getRoomStatus() == 1){
            playerInfo.setIsWatch(1);
        }else {
            playerInfo.setIsWatch(0);
        }
        roomInfo.getAllPlayerMap().put(playerInfo.getPlayerId(), playerInfo);

    }


    /**
     * 获取对象缓存
     */
    public RoomInfo getObjCacheByKey(String roomId) {
        return caffeineCache.getIfPresent(roomId);
    }

    /**
     * 根据key删除缓存
     */
    public void removeCacheByKey(String roomId) {
        caffeineCache.asMap().remove(roomId);
    }

    public boolean contains(String roomId){
        return caffeineCache.asMap().containsKey(roomId);
    }


    public String createRoomId(){
        String roomId = RandomUtil.randomString(RandomUtil.BASE_NUMBER, 6);
        if (caffeineCache.asMap().containsKey(roomId)){
            return createRoomId();
        }
        return roomId;
    }


    public void setPlayerRoom(String playerId, String roomId){
        playerRoomCache.put("play-" + playerId, roomId);
    }

    public String getRoomIdByPlayerId(String playerId){
        return playerRoomCache.asMap().get("play-" + playerId);
    }

    public void removePlayerRoom(String playerId){
        playerRoomCache.asMap().remove(playerId);
    }



}